package com.yao.dubboconsumer.client;

import com.yao.dubboapi.entity.InvokeMessage;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.LineBasedFrameDecoder;
import io.netty.handler.codec.serialization.ClassResolvers;
import io.netty.handler.codec.serialization.ObjectDecoder;
import io.netty.handler.codec.serialization.ObjectEncoder;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

import java.lang.reflect.Method;

/**
 * @author Henry Yao
 * @since 2021/5/3
 */
public class NettyClientConsumer {
    public Object doRpc(Method method, Object[] args, String provider,String className) {
        NettyClientConsumerHandler handler = new NettyClientConsumerHandler();
        NioEventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(group)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            ChannelPipeline pipeline = socketChannel.pipeline();
                            pipeline.addLast(new ObjectEncoder());
                            pipeline.addLast(new ObjectDecoder(ClassResolvers.cacheDisabled(null)));
                            pipeline.addLast(handler);
                        }
                    });
            String host = provider.split(":")[0];
            int port = Integer.parseInt(provider.split(":")[1]);
            ChannelFuture future = bootstrap.connect(host, port).sync();
            // 封装invokeMessage对象
            InvokeMessage invokeMessage = new InvokeMessage();
            invokeMessage.setClassName(className);
            invokeMessage.setMethodName(method.getName());
            invokeMessage.setParameterTypes(method.getParameterTypes());
            invokeMessage.setParameterValues(args);
            // 发送
            future.channel().writeAndFlush(invokeMessage);
            future.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            group.shutdownGracefully();
        }
        return handler.getResult();
    }
}
